<template>
  <div class="out">
    <van-search
      v-model="value"
      @keydown.13="searchGoods"
      @clear="searchGoods"
      shape="round"
      show-action
      placeholder="请输入搜索关键词"
      @cancel="onCancel"
    />
    <main v-if="searchArr.length == 0">
      <template v-if="searchHistory.length > 0">
        <p>搜索记录</p>
        <van-tag v-for="(v, i) in searchHistory" :key="i" round type="primary" @click="goSearch(v)">
          {{ v }}
          <van-icon name="cross" @click.stop="deletaSearchHistory(v)" />
        </van-tag>
      </template>

      <p>热门搜索</p>
      <van-tag v-for="v in hotHistory" :key="v.id" round type="danger ">
        {{ v.recommandText }}
        <i class="iconfont icon-huo"></i>
      </van-tag>
    </main>
    <ul v-else>
      <template v-if="this.searchArr[0].dealid">
        <storeMoreMain v-for="v in this.searchArr" :v="v" :key="v.dealid" />
      </template>
      <template v-else>
        <div>{{ searchArr[0] }}</div>
      </template>
    </ul>
  </div>
</template>

<script>
import getLink from '@/api/getLink.js';
import getdata from '@/api/getdata.js';
import storeMoreMain from '@/components/whs/store/storeMore-main.vue';

export default {
  components: { storeMoreMain },
  data() {
    return {
      value: '',
      hotHistory: [],
      searchArr: [],
      searchHistory: [],
    };
  },
  created() {
    getLink('/api/search').then(ok => (this.hotHistory = ok.data));
    if (window.localStorage.getItem('searchHistory')) {
      this.searchHistory = JSON.parse(window.localStorage.getItem('searchHistory'));
    }
  },
  methods: {
    onCancel() {
      this.$router.go(-1);
    },
    searchGoods() {
      if (!this.value) {
        this.searchArr = [];
      } else {
        this.searchHistory.push(this.value);
        window.localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
        getdata('/apidl/store/serach', { name: this.value }).then(ok => {
          this.searchArr = ok.data;
          if (!ok.data.length) {
            this.searchArr.push('搜索为空');
          }
        });
      }
    },
    //跳转搜索
    goSearch(v) {
      getdata('/apidl/store/serach', { name: v }).then(ok => {
        this.searchArr = ok.data;
        if (!ok.data.length) {
          this.searchArr.push('搜索为空');
        }
      });
    },
    //删除搜索记录
    deletaSearchHistory(v) {
      let arr = JSON.parse(window.localStorage.getItem('searchHistory'));
      this.searchHistory = arr.filter(ele => ele != v);
      window.localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
    },
  },
};
</script>

<style lang="less" scoped>
.out {
  font-size: 0.3rem;
  main {
    padding: 0 0.3rem;
    p {
      margin: 0.2rem 0;
    }
    .van-tag {
      padding: 0.2rem;
      margin: 0.1rem;
    }
  }
}
ul {
  padding: 0.3rem;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
</style>
